<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of OrderController
 *
 * @author Vu
 */
include APPLICATION_PATH."/models/Order.php";
include APPLICATION_PATH."/models/Order_Detail.php";
include APPLICATION_PATH."/models/Product.php";
include APPLICATION_PATH."/models/Agent.php";
class Admin_OrderController extends Zend_Controller_Action {
    //put your code here
    public function init(){
        $bootstrap = $this->getInvokeArg("bootstrap");
        $this->aConfig = $bootstrap->getOptions();
        $this->view->aConfig = $this->aConfig;
        $this->model = new Model_Order();
        $this->modelMapper = new Model_OrderMapper();
        $this->Detailmodel=new Model_Order_Detail();
        $this->DetailmodelMapper = new Model_Order_DetailMapper();
        $this->Productmodel=new Model_Product();
        $this->ProductmodelMapper = new Model_ProductMapper();
        $this->Agentmodel=new Model_Agent();
        $this->AgentmodelMapper=new Model_AgentMapper();
    }
    
    public function indexAction(){
        
    }
     
    public function listAction(){
        
    }    
    
    public function orderAction(){
         $this->view->storeHTML= GlobalLib::getComboByStore('store_id','agent' , 'id', 'name', 0,false,'form-control','','','','');
        $this->view->agentHTML= GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name',0,false,'form-control','','','','onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'admin/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML= GlobalLib::getComboByProduct('product_id','product','id','name',0,false,'form-control','','','','onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'admin/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#area_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        //        
        $this->view->popupareaHTML= GlobalLib::getComboByArea('popup_area_id', 'area', 'id', 'name', 0,false, 'form-control','', '','','onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'admin/service/index\',$(\'#popup_area_id\').val(),\'popup_province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupprovinceHTML= GlobalLib::getComboByProvince('popup_province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= 0 )', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'admin/service/index\',$(\'#popup_province_id\').val(),\'popup_district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupdistrictHTML=GlobalLib::getComboByDistrict('popup_district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id= 0');   
    }
    public function serviceAction(){
        $this->_helper->layout->disableLayout();
        foreach ($this->modelMapper->fetchAllByAdmin() as $items) {
            $allnew = TRUE;
            //Kiểm tra các chi tiết đều ở tình trạng hủy thì tình trạng đơn hàng là Hủy
            $stt = 0;
            $sttCancell = 0;
            foreach ($this->DetailmodelMapper->fetchAllByOrderNo($items['order_no']) as $detailitem) {
                if ($items['order_no'] == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() > 1) {
                    $allnew = FALSE;
                }
                $stt++;
                if ($items['order_no'] == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() == 3) {
                    $sttCancell++;
                }
            }
            if (!$allnew && $items['order_status'] == '1')
                $order_status_name = "Đang chờ duyệt";
            else
                $order_status_name = GlobalLib::getName("order_status", $items['order_status'], "name");
            if ($stt == $sttCancell) {
                $order_status_name = "Hủy";
            }
            if($items['agent_name']==""){
                $agent_name="Tên cửa hàng đã bị xoá";
            } else {
                $agent_name=$items['agent_name'];
            }
            $menber[] = array(
                'id' => $items['order_id'],
                'store_name' => $agent_name,
                'order_no' => $items['order_no'],
                'total_charges' => $items['total_charges'],
                'created' => ($items['created']),
                'order_status' => $order_status_name
            );
        }
        echo json_encode($menber);
        exit();
    }
    public function servicedetailAction(){
        $this->_helper->layout->disableLayout();
        $order_id=$this->getParam("order_id","0");
        foreach ($this->DetailmodelMapper->fetchAllByOrderNo($order_id) as $items ) 
        {                          
            if($items->getModified_By()==0){
                    $modified_by = "";
                }else{
                    $firt_name = GlobalLib::getName ("admin",$items->getModified_By() ,'first_name');
                    $last_name = GlobalLib::getName ("admin",$items->getModified_By() ,'last_name');
                    $modified_by=$firt_name.' '.$last_name;
                }
                $product_name = "Sản phẩm đã bị xoá!";                        
                if($this->ProductmodelMapper->findIn($items->getProduct_Id())!=null)
                    $product_name = GlobalLib::getName('product', $items->getProduct_Id(),'name');   
                $order_status = GlobalLib::getName("order_status", $items->getOrder_Status_Id() ,"name");
                $agent_name="Tên đại lý đã bị xoá";
                if($this->AgentmodelMapper->findbyagentid($items->getAgent_Id(),$this->Agentmodel)!=NULL)
                        $agent_name=GlobalLib::getName("agent", $items->getAgent_Id(), "name");
                $menber[]=array(
                    'id'=>$items->getId(),
                    'product_name'=>  $product_name,
                    'quantity'=> $items->getQuantity(),
                    'price'=>$items->getPrice(),
                    'factor'=>  $items->getFactor(),
                    'charges'=>  $items->getCharges(),
                    'agent_name'=> $agent_name,
                    'order_status_name' =>  $order_status,
                    'modified'=> GlobalLib::viewDate($items->getModified()),
                    'modified_by' => $modified_by,
                    'order_status_id' => $items->getOrder_Status_Id(),
                );
        }
        echo json_encode($menber);
        exit();
    }
    public  function detailAction()
    {
        $id = $this->_getParam("id","0");
        $this->modelMapper->find($id,$this->model);
        $agent_name="Tên đại lý đã bị xoá";
        if($this->AgentmodelMapper->findbyagentid($this->model->getStore_Id(),$this->Agentmodel)!=NULL)
            $agent_name=GlobalLib::getName("agent", $this->model->getStore_Id(), "name");
        $this->view->agent_name=$agent_name;
        $this->view->item = $this->model;           
    }
     public function addorderAction() {     
            $redirectUrl = $this->aConfig["site"]["url"] . "/admin/order/index";            
            $order_no = GlobalLib::createOrderNo();
            $agent_id = $this->_getParam("store_id","");
            $total_charges=$this->_getParam("total_charges","");
            $this->model->setStore_Id($agent_id);
            $this->model->setTotal_Price(0);
            $this->model->setTotal_Charges($total_charges);
            $this->model->setOrder_No($order_no);
            $this->model->setCreated(date("Y/m/d H:i:s"));
            $this->model->setCreated_By(1);
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
            $this->AgentmodelMapper->find($agent_id,$this->Agentmodel);
            $sum_store_charges=  $this->Agentmodel->getCharges()+$total_charges;
            $this->Agentmodel->setCharges($sum_store_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);
            echo $order_no;
            exit();
    }
    public function adddetailAction() {                
        $order_no = $this->getParam("order_no","0");
        if($order_no=="0")
        {
            $this->_redirect($this->aConfig["site"]["url"] . "/admin/order/index");
        }
        $product_id = $this->_getParam("product_id","0");
        $quantity = $this->_getParam("quantity","0");
        $agent_id = $this->_getParam("agent_id","0");
        $factor = $this->_getParam("factor","0");
        $charges = $this->_getParam("charges","0");
        $order_created = $this->_getParam("order_created","0");
        $this->Detailmodel->setOrder_Created(GlobalLib::toMysqlDateString($order_created));
        $this->Detailmodel->setOrder_Id($order_no);
        $this->Detailmodel->setProduct_Id($product_id);
        $this->Detailmodel->setQuantity($quantity);
        $this->Detailmodel->setAgent_Id($agent_id);
        $this->Detailmodel->setFactor($factor);
        $this->Detailmodel->setPrice(0);
        $this->Detailmodel->setCharges($charges);
        $this->Detailmodel->setOrder_Status_Id(2);
        $this->Detailmodel->setModified(date("Y/m/d H:i:s"));
        $this->Detailmodel->setModified_By(GlobalLib::getLoginId());
        $this->DetailmodelMapper->save($this->Detailmodel);
        echo $order_no;
        exit();
    }
    public function browserAction() {
        $id = $this->_getParam("id","0");
        // get order_detail
        $this->DetailmodelMapper->find($id,$this->Detailmodel);
        // thay doi trang thai order_detail
        $this->Detailmodel->setOrder_Status_Id(2);
        $this->Detailmodel->setModified(date("Y/m/d H:i:s"));
        $this->Detailmodel->setModified_By(GlobalLib::getLoginId());
        $this->DetailmodelMapper->save($this->Detailmodel);        
        // lay order_id
        $order_id = $this->Detailmodel->getOrder_Id();
        // get order
        foreach ($this->modelMapper->fetchAll() as $items)
        {
            if($items->getOrder_No()==$order_id)  
            {
                $this->model = $items;
            }                        
        }
        // tich diem cho order
        $sum_order_charges =0;
        foreach($this->DetailmodelMapper->fetchAll() as $items)
        {            
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==2)
            {
                $sum_order_charges += $items->getCharges();
            }    
        }
        $this->model->setTotal_Charges($sum_order_charges);  
        $this->modelMapper->save($this->model);
        // kiem tra order_detail -> thay doi trang thai order
        $checkorder =TRUE;
        foreach($this->DetailmodelMapper->fetchAll() as $items)
        {
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==1)
            {    
                $checkorder = FALSE;
            }            
        }
        if($checkorder) 
        {
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
        }
        // update diem cho store
        $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);        
        $sum_store_charges = 0;
        foreach ($this->modelMapper->fetchAll() as $items)
        {                   
            if($items->getStore_Id()==$this->Agentmodel->getId())
                $sum_store_charges+= $items->getTotal_Charges();
        }
        $this->Agentmodel->setCharges($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // update diem cho agent
        $this->AgentmodelMapper->find($this->Detailmodel->getAgent_Id(),$this->Agentmodel);        
        $sum_agent_charges = 0;
        foreach ($this->DetailmodelMapper->fetchAll() as $items)
        {                   
            if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                $sum_agent_charges+= $items->getCharges();
        }                
        $this->Agentmodel->setCharges_Sell($sum_agent_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // redirect
        $this->_redirect($this->aConfig["site"]["url"].'admin/order/detail/id/'.$this->model->getId());
    }
    public function cancelAction() {
        $id = $this->_getParam("id","0");
        // get order_detail
        $this->DetailmodelMapper->find($id,$this->Detailmodel);
        // thay doi trang thai order_detail
        $this->Detailmodel->setOrder_Status_Id(3);
        $this->Detailmodel->setModified(date("Y/m/d H:i:s"));
        $this->Detailmodel->setModified_By(GlobalLib::getLoginId());
        $this->DetailmodelMapper->save($this->Detailmodel);        
        // lay order_id
        $order_id = $this->Detailmodel->getOrder_Id();
        // get order
        foreach ($this->modelMapper->fetchAll() as $items)
        {
            if($items->getOrder_No()==$order_id)  
            {
                $this->model = $items;
            }                        
        }
        // tich diem cho order
        $sum_order_charges =0;
        foreach($this->DetailmodelMapper->fetchAll() as $items)
        {            
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==2)
            {
                $sum_order_charges += $items->getCharges();
            }    
        }
        $this->model->setTotal_Charges($sum_order_charges);  
        $this->modelMapper->save($this->model);
        // kiem tra order_detail -> thay doi trang thai order
        $checkorder =TRUE;
        foreach($this->DetailmodelMapper->fetchAll() as $items)
        {
            if($items->getOrder_Id()==$order_id && $items->getOrder_Status_Id()==1)
            {    
                $checkorder = FALSE;
            }
        }
        if($checkorder) 
        {
            $this->model->setOrder_Status_Id(2);
            $this->modelMapper->save($this->model);
        }
        // update diem cho store
        $this->AgentmodelMapper->find($this->model->getStore_Id(),$this->Agentmodel);        
        $sum_store_charges = 0;
        foreach ($this->modelMapper->fetchAll() as $items)
        {                   
            if($items->getStore_Id()==$this->Agentmodel->getId())
                $sum_store_charges+= $items->getTotal_Charges();
        }
        $this->Agentmodel->setCharges($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // update diem cho agent
        $this->AgentmodelMapper->find($this->Detailmodel->getAgent_Id(),$this->Agentmodel);        
        $sum_store_charges = 0;
        foreach ($this->DetailmodelMapper->fetchAll() as $items)
        {                   
            if($items->getAgent_Id()==$this->Agentmodel->getId()&&$items->getOrder_Status_Id()==2)
                $sum_store_charges+= $items->getCharges();
        }
        $this->Agentmodel->setCharges_Sell($sum_store_charges);
        $this->AgentmodelMapper->save($this->Agentmodel);
        // redirect
        $this->_redirect($this->aConfig["site"]["url"].'admin/order/detail/id/'.$this->model->getId());    
    }
}
